<?php


namespace App\Services\pay;


use App\Models\HouseAudit;
use App\Models\Order;
use App\Models\RentAndPurchase;
use App\Services\ElasticSearchService;
use App\Tools\ConnectRedis;
use App\Tools\RedisTools;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AliPayType implements PayFactory
{
    public $redis;
    public function __construct()
    {
        $this->redis=(RedisTools::getInstance())->connectRedis();
    }

    /**
     * @Notes:支付
     * @Author:Planb,
     * @Date: 2022/11/12,
     * @Time: 10:13,
     */
    public function pay($out_trade_no,$subject,$total_amount,$body){

        //载入配置
        require_once './alipay/pagepay/service/AlipayTradeService.php';
        require_once './alipay/pagepay/buildermodel/AlipayTradePagePayContentBuilder.php';
        $config = config('pay.alipay');

        //构造参数
        $payRequestBuilder = new \AlipayTradePagePayContentBuilder();
        $payRequestBuilder->setBody($body);
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setTotalAmount($total_amount);
        $payRequestBuilder->setOutTradeNo($out_trade_no);

        $aop = new \AlipayTradeService($config);

        /**
         * pagePay 电脑网站支付请求
         * @param $builder 业务参数，使用buildmodel中的对象生成。
         * @param $return_url 同步跳转地址，公网可以访问
         * @param $notify_url 异步通知地址，公网可以访问
         * @return $response 支付宝返回的信息
         */

        $response = $aop->pagePay($payRequestBuilder, $config['return_url'], $config['notify_url']);
        dd();
    }

    /**
     * @Notes:同步
     * @Author:Planb,
     * @Date: 2022/11/12,
     * @Time: 10:13,
     */
    public function sync(){

        require_once './alipay/pagepay/service/AlipayTradeService.php';
        $config = config('pay.alipay');
        $arr = $_GET;
        $alipaySevice = new \AlipayTradeService($config);
        $result = $alipaySevice->check($arr);
        if ($result) {//验证成功
            //商户订单号
            $out_trade_no = htmlspecialchars($_GET['out_trade_no']);
            //支付宝交易号
            $trade_no = htmlspecialchars($_GET['trade_no']);
            echo "验证成功<br />支付宝交易号：" . $trade_no;
            //return view('wx');
        } else {
            //验证失败
            echo "验证失败";
        }
    }

    /**
     * @Notes:异步
     * @Author:Planb,
     * @Date: 2022/11/12,
     * @Time: 10:14,
     */
    public function notify($arr){
        require_once './alipay/pagepay/service/AlipayTradeService.php';
        $config = config('pay.alipay');
        $alipaySevice = new \AlipayTradeService($config);
        $alipaySevice->writeLog(var_export($_POST, true));
        $result = $alipaySevice->check($arr);
        if($result) {//验证成功
            $out_trade_no = $arr['out_trade_no'];
            //支付宝交易号
            $trade_no = $arr['trade_no'];
            //交易状态
            $trade_status = $arr['trade_status'];
            if($arr['trade_status'] == 'TRADE_FINISHED') {
              //交易完成不做操作
            }
            else if ($arr['trade_status'] == 'TRADE_SUCCESS') {
                //交易成功
                $orderInfo = Order::where('order_sn',$out_trade_no)->first();
                $this->redis->set('a',$orderInfo);
                DB::beginTransaction();
                switch ($orderInfo['order_type']){
                    case 1:
                        try {
                        Order::where('order_sn',$out_trade_no)->update([
                            'pay_status'=>1,
                            'updated_at'=>date('Y-m-d H:i:s'),
                            'pay_type'=>1
                        ]);
                        $houseAudit= HouseAudit::where('id',$orderInfo['house_id'])->first();
                        HouseAudit::where('id',$orderInfo['house_id'])->update([
                            'pay_status'=>1,
                            'updated_at'=>date('Y-m-d H:i:s')
                        ]);
                        DB::commit();
                        break;
                    }catch (\Exception $exception){
                        Log::info($trade_no.'---'.$exception->getMessage());
                        DB::rollBack();
                        break;
                    }
                    case 2:
                        try {
                            Order::where('order_sn',$out_trade_no)->update([
                                'pay_status'=>1,
                                'updated_at'=>date('Y-m-d H:i:s'),
                                'pay_type'=>1
                            ]);
                            $houseAudit= HouseAudit::where('id',$orderInfo['house_id'])->first();
                            HouseAudit::where('id',$orderInfo['house_id'])->update([
                                'pay_status'=>1,
                                'updated_at'=>date('Y-m-d H:i:s')
                            ]);
                            DB::commit();
                            break;
                        }catch (\Exception $exception){
                            Log::info($trade_no.'---'.$exception->getMessage());
                            DB::rollBack();
                            break;
                        }

                    case 3:
                        try {
                            Order::where('order_sn',$out_trade_no)->update([
                                'pay_status'=>1,
                                'updated_at'=>date('Y-m-d H:i:s'),
                                'pay_type'=>1
                            ]);
                            RentAndPurchase::where('id',$orderInfo['house_id'])->where('uid',$orderInfo['uid'])->update([
                                'house_price_type'=>1
                            ]);

//                            $data=RentAndPurchase::where('id',$orderInfo['house_id'])->where('uid',$orderInfo['uid'])->first()->toArray();
//                            (ElasticSearchService::getInstance())->createOrdinary("list",$data);
                            DB::commit();
                        }catch (\Exception $exception){
                            Log::info($trade_no.'---'.$exception->getMessage());
                            DB::rollBack();
                        }

                        break;

                }

            }
            echo "success";	//请不要修改或删除
        }else {
            //验证失败[
            echo "fail";

        }
    }
}
